package com.lghs.stutor;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.*;
import android.support.v4.app.NotificationCompat;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Session extends Activity implements Alertresponder {

    Vital vital = new Vital();
    // Activity Variables
    static String url, username, message, tutorname, type, subject, sessionid;
    static int lastmessageid;
    static boolean initialmessage, Icanhasbuttonback;
    // ---
    Bundle b;
    Intent i;
    // ---
    EditText et_message;
    ListView lv_messages;
    Button btn_send;
    EditText et1;
    // ---
    HttpGet httpGet;
    HttpResponse execute;
    DefaultHttpClient client;
    InputStream content;
    BufferedReader buffer;
    // ---
    ArrayList<String> listItems;
    ArrayAdapter<String> adapter;
    // ---
    Handler handler;
    Runnable runnable;

    PowerManager pm;
    PowerManager.WakeLock wakeLock;
    int mId = 1;
    boolean newnotifications;
    NotificationCompat.Builder mBuilder;
    NotificationManager mNotificationManager;
    ConnectivityManager cm;
    Toast msg;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(com.lghs.stutor.R.layout.activity_session);
        initialization();
    }

    public void onBackPressed() {
        vital.alertsystem(Session.this, "Leave session", "Are you sure you wish to leave this session?", "12", "idk", "Yes", "No", "");
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void initialization() {
        b = getIntent().getExtras();
        sessionid = "";
        pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK, "activesession");
        url = "";
        username = "";
        username = b.getString("uname");
        cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        tutorname = "";
        if (b.getString("tutorname") != null)
            tutorname = b.getString("tutorname");
        lastmessageid = 0;
        sessionid = b.getString("sessionid");
        type = "";
        if (b.getString("type") != null)
            type = b.getString("type");
        subject = "";
        if (b.getString("subject") != null)
            subject = b.getString("subject");
        initialmessage = false;
        Icanhasbuttonback = true;
        listItems = new ArrayList<String>();
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, listItems);
        declaredcomponents();
        listeners();
        lv_messages.setAdapter(adapter);
        handler = new Handler();
        if (type.equals("student")) {
            message = "Hello I am " + username;
            initialmessage = true;
            btn_send.performClick();
        }
        wakeLock.acquire();
        newnotifications = false;
        mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.idk)
                        .setContentTitle("Initi notification")
                        .setContentText("LoL World!");
        Intent resultIntent = new Intent(this, Session.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(Session.this);
        stackBuilder.addParentStack(Login.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);
        mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        recheck();
    }

    @Override
    protected void onPause() {
        super.onPause();
        newnotifications = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        newnotifications = false;
    }

    public void declaredcomponents() {
        et_message = (EditText) findViewById(com.lghs.stutor.R.id.session_edittext_sendmessage);
        lv_messages = (ListView) findViewById(com.lghs.stutor.R.id.session_listview_messages);
        btn_send = (Button) findViewById(com.lghs.stutor.R.id.session_button_sendmessage);
        et1 = (EditText) findViewById(R.id.session_edittext_sendmessage);
    }

    public void listeners() {
        btn_send.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                message = et1.getText().toString().trim();
                message = message.replace(" ", "%20");
                message = message.replace("+", "{/001}");
                if (!message.equals("")) {
                    Icanhasbuttonback = false;
                    btn_send.setEnabled(false);
                    btn_send.setText("Sending...");
                    new sendmessage().execute();
                    et1.setText("");
                }
            }
        });
        et_message.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
                if (arg2.getAction() == KeyEvent.ACTION_DOWN
                        && arg1 == KeyEvent.KEYCODE_ENTER) {
                    btn_send.performClick();
                }
                return false;
            }

        });
    }

    public void recheck() {
        // Loops WEEEEEEEEEEEE
        runnable = new Runnable() {
            public void run() {
                vital.checkInternetConnection(Session.this, cm);
                new getmessages().execute();
                if (btn_send.isEnabled() == false && Icanhasbuttonback == true) {
                    btn_send.setEnabled(true);
                    btn_send.setText("Send");
                }
                handler.postDelayed(this, 3500);
            }
        };
        handler.postDelayed(runnable, 100);
    }

    @Override
    public void buttonhandler(int number) {
        switch (number) {
            case 1:
                if (msg.getView() != null)
                    msg.cancel();
                handler.removeCallbacks(runnable);
                wakeLock.release();
                i = new Intent();
                i.putExtra("firstlaunch", "no");
                i.putExtra("uname", username);
                if (!type.equals("student"))
                    i.setClass(getApplicationContext(), Home.class);
                else {
                    i.setClass(getApplicationContext(), ReviewSession.class);
                    i.putExtra("listli", listItems);
                    i.putExtra("tutorname", tutorname);
                    i.putExtra("uname", username);
                    i.putExtra("sessionid", sessionid);
                    i.putExtra("type", type);
                }
                startActivity(i);
                finish();
                break;
            case 2:
                recheck();
        }
    }

    @Override
    public void internethandler(int number) {
        msg = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
        switch (number) {

            case 1:
                if (msg.getView() != null)
                    msg.cancel();
                break;
            case 2:
                msg = Toast.makeText(getApplicationContext(), "INTERNET CONNECTION IS NOT PRESENT", Toast.LENGTH_SHORT);
                msg.show();
                break;
        }
    }

    class sendmessage extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        protected String doInBackground(String... urls) {
            String response = "";
            url = "http://" + vital.host + "/sendmessage.php?u=" + username
                    + "&t=" + type + "&sj=" + subject + "&s=" + sessionid
                    + "&m=" + message + "";

            try {
                client = new DefaultHttpClient();
                httpGet = new HttpGet(url);
                execute = client.execute(httpGet);
                content = execute.getEntity().getContent();

                buffer = new BufferedReader(new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    response = s;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }

        @Override
        protected void onPostExecute(String result) {
            new getmessages().execute();
            Icanhasbuttonback = true;
        }
    }

    class getmessages extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        protected String doInBackground(String... urls) {
            String response = "";
            url = "http://" + vital.host + "/getmessages.php?s=" + sessionid
                    + "&mr=" + lastmessageid + "&t=" + type;
            try {
                client = new DefaultHttpClient();
                httpGet = new HttpGet(url);
                execute = client.execute(httpGet);
                content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    if (s.contains("-")) {
                        s = s.replace("{/001}", "+");
                        s = s.trim();
                        lastmessageid = Integer.valueOf(s.substring(0,
                                s.indexOf("-")));
                        s = s.replaceFirst(String.valueOf(lastmessageid), "");
                        s = s.replaceFirst("-", "");
                        listItems.add(s);
                        response = s;
                        mBuilder =
                                new NotificationCompat.Builder(Session.this)
                                        .setSmallIcon(R.drawable.notification)
                                        .setContentTitle("Last Message")
                                        .setContentText(s);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }

        protected void onPostExecute(String result) {
            if (!result.trim().equals("")) {
                adapter.notifyDataSetChanged();
                if (newnotifications)
                    mNotificationManager.notify(mId, mBuilder.build());
            }
        }
    }
}